import React, { Component } from 'react'
import './App.css'
import { imagePdf, PdfBase64,info } from './main'
import initFont from 'jspdf-font'
import { Button } from 'antd'
import { Upload, message } from 'antd'
import { InboxOutlined } from '@ant-design/icons'

const { Dragger } = Upload

class App extends Component {
  constructor(props) {
    super(props)
    this.handleChange = this.handleChange.bind(this)
    this.handleClick = this.handleClick.bind(this)
    this.state = {
      imagesData: [
        {
          width: 730,
          height: 1389,
          data: '',
          title:''
        },
      ],
      info:info,
      loading:false
    }
    let that=this;
    Object.defineProperty(info,'loading',{
      get() { return this.state.loading },
      set(newValue) { 
        that.setState({
        loading:newValue
      })},
    })
  }
  names = []
  fileList = []
  times = 0;
  isPrimary=false
  myprops = {
    name: 'file',
    multiple: true,
    fileList:[],
    action: 'https://127.0.0.1:3000',
    beforeUpload: async (file, fileList) => {
      this.fileList = fileList
      const imgs = document.getElementById('imgs')
      imgs.innerHTML = ''
      setTimeout(async () => {
        ++this.times
        if (this.times == fileList.length) {
          await this.getImageData()
          this.isPrimary=true;
          const { imagesData = [] } = this.state
          for (let i = 0; i < fileList.length; i++) {
            let img = new Image()
            img.src = imagesData[i].data
            let div = document.createElement('div')
            let p = document.createElement('p')
            p.innerText = this.names[i]
            div.appendChild(img)
            div.appendChild(p)
            div.setAttribute('draggable',true)
            imgs.appendChild(div)
            setTimeout(()=>{
              this.dragHandler()
            }) 
          }
          this.times=0
        } 
      })

      return false
    },
    onDrop(e) {
      // console.log('Dropped files', e.dataTransfer.files)
    },
  }
  handleChange(e) {
    var data = e.target.value
    this.setState({
      imagesData: JSON.parse(data),
    })
  }
  dragHandler() {
    // 用来存取被拖拽的节点
    let draggedNode = null
    // 获取可拖拽节点
    const dragNodes = document.querySelectorAll('div[draggable="true"]')
    // 给可拖拽节点绑定相关事件
    dragNodes.forEach(item => {
      item.ondragstart = () => {
        draggedNode = item
      }
      // 默认情况下,数据/元素不能在其他元素中被拖放,也就是会阻止你做drop操作，所以取消其默认行为
      item.ondragover = e => {
        e.preventDefault()
      }
      // 被拖拽的节点，被释放后进行节点替换
      item.ondrop = e => {
        if (draggedNode !== null && draggedNode !== item) {
          const temp = document.createElement('div')
          const dragBox = document.getElementById('imgs')
          dragBox.replaceChild(temp, e.target.parentNode)
          dragBox.replaceChild(e.target.parentNode, draggedNode)
          dragBox.replaceChild(draggedNode, temp)
          let divs = [...dragBox.children];
          let names = []
          let imagesData=[]
          divs.forEach(e=>{
            let child = [...e.children]
            let img = child[0]
            let p = child[1]
            names.push(p.innerText)
            imagesData.push(img.getAttribute('src'))
          })
          this.names=names
          imagesData.forEach((e,i)=>{
            const detail = this.state.imagesData.find(ee=>ee.data == e);
            imagesData[i]=detail
          })
          this.setState({
            imagesData
          })
          this.isPrimary=false
        }
      }
    })
  }
  async transferToBase64(file) {
    if (typeof FileReader === 'function') {
      let base64 = ''
      const reader = new FileReader()
      await reader.readAsDataURL(file)
      await new Promise(r => {
        reader.onload = event => {
          base64 = event.target.result
          r(true)
        }
      })
      return base64
    } else {
      return ''
    }
  }
  rotateBase64Img(src, edg, callback) {
    var canvas = document.createElement('canvas')
    var ctx = canvas.getContext('2d')

    var imgW //图片宽度
    var imgH //图片高度
    var size //canvas初始大小

    if (edg % 90 != 0) {
      console.error('旋转角度必须是90的倍数!')
      throw '旋转角度必须是90的倍数!'
    }
    edg < 0 && (edg = (edg % 360) + 360)
    const quadrant = (edg / 90) % 4 //旋转象限
    const cutCoor = { sx: 0, sy: 0, ex: 0, ey: 0 } //裁剪坐标

    var image = new Image()
    image.crossOrigin = 'anonymous'
    image.src = src

    image.onload = function () {
      imgW = image.width
      imgH = image.height
      size = imgW > imgH ? imgW : imgH

      canvas.width = size * 2
      canvas.height = size * 2
      switch (quadrant) {
        case 0:
          cutCoor.sx = size
          cutCoor.sy = size
          cutCoor.ex = size + imgW
          cutCoor.ey = size + imgH
          break
        case 1:
          cutCoor.sx = size - imgH
          cutCoor.sy = size
          cutCoor.ex = size
          cutCoor.ey = size + imgW
          break
        case 2:
          cutCoor.sx = size - imgW
          cutCoor.sy = size - imgH
          cutCoor.ex = size
          cutCoor.ey = size
          break
        case 3:
          cutCoor.sx = size
          cutCoor.sy = size - imgW
          cutCoor.ex = size + imgH
          cutCoor.ey = size + imgW
          break
      }

      ctx.translate(size, size)
      ctx.rotate((edg * Math.PI) / 180)
      ctx.drawImage(image, 0, 0)

      var imgData = ctx.getImageData(
        cutCoor.sx,
        cutCoor.sy,
        cutCoor.ex,
        cutCoor.ey
      )
      if (quadrant % 2 == 0) {
        canvas.width = imgW
        canvas.height = imgH
      } else {
        canvas.width = imgH
        canvas.height = imgW
      }
      ctx.putImageData(imgData, 0, 0)
      callback(canvas.toDataURL())
    }
  }
  async getImageData() {
    let files = this.fileList
    let data = []
    let names = []
    for (let i = 0; i < files.length; i++) {
      let e = files[i]
      let name = e.name.slice(0, e.name.lastIndexOf('.'))
      let imgType = e.name.slice(e.name.lastIndexOf('.') + 1)
      names.push(name)
      let base64 = await this.transferToBase64(files[i])
      let img = new Image()
      let width = 0,
        height = 0 //手动创建一个Image对象
      img.src = window.URL.createObjectURL(e)
      await new Promise(r => {
        img.onload = function () {
          width = this.width
          height = this.height
          r()
        }
      })
      if (width > height) {
        await new Promise(r => {
          this.rotateBase64Img(base64, 90, data => {
            base64 = data
            r()
          })
        })
        let newWidth = height
        height = width
        width = newWidth
      }
      data.push({
        width: width,
        type: 'image',
        height: height,
        data: base64,
        imgType,
      })
    }
    this.names = names
    this.setState({
      imagesData: data,
    })
  }
  async handleClick(that, allInOne = false) {
    if(this.isPrimary) await this.getImageData()
    const { imagesData = [] } = this.state
    if (allInOne) {
      imagePdf(imagesData, '合并PDF', {
        initFont,
      })
      return
    }
    this.names.forEach((e, i) => {
      imagePdf(imagesData[i], e, {
        initFont,
      })
    })
  }
  async saveClick(that, allInOne = false) {
    if(this.isPrimary)  await this.getImageData()
    const { imagesData = [] } = this.state
    if (allInOne) {
      PdfBase64(imagesData, '合并PDF', {
        initFont,
      })
      return
    }
    this.names.forEach((e, i) => {
      PdfBase64(imagesData[i], e, {
        initFont,
      })
    })
  }
  render() {
    const { imagesData = [] } = this.state
    const _imagesData = JSON.stringify(imagesData)
    return (
      <div>
        <div id='imgs'></div>
        <div className='content' id='App'>
          <div>
            <Dragger {...this.myprops}>
              <p className='ant-upload-drag-icon'>
                <InboxOutlined />
              </p>
              <p className='ant-upload-text'>点击或者拖拽上传</p>
            </Dragger>
          </div>
          <div className='btns'>
            <div>
              <Button type='primary' onClick={this.handleClick}>
                单张下载
              </Button>
            </div>
            <div>
              <Button
                type='primary'
                onClick={this.handleClick.bind(this, true)}
              >
                合并下载
              </Button>
            </div>
            <div>
              <Button type='primary' onClick={this.saveClick.bind(this)} loading={this.state.loading}>
                单张保存
              </Button>
            </div>
            <div>
              <Button type='primary' onClick={this.saveClick.bind(this, true)}  loading={this.state.loading}>
                合并保存
              </Button>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

export default App
